package com.x.crm.interceptor;

import com.alibaba.fastjson.JSON;
import com.x.crm.controller.SessionKey;
import com.x.crm.http.response.BaseResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class SessionTimeoutInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        Object account = httpServletRequest.getSession().getAttribute(SessionKey.account);
        if(account == null){
            BaseResponse response = BaseResponse.timeout("会话超时，请重新登录!");
            httpServletResponse.setCharacterEncoding("UTF-8");
            String requestContentType = httpServletRequest.getContentType();
            String responseContentType = StringUtils.isBlank(requestContentType)?"text/html;charset=UTF-8":requestContentType;
            if(false == StringUtils.contains(responseContentType.toLowerCase(),"charset=")){
                responseContentType = responseContentType + ";charset=UTF-8";
            }
            httpServletResponse.setContentType(responseContentType);
            PrintWriter out = null;
            try {
                out = httpServletResponse.getWriter();
                out.append(JSON.toJSONString(response));
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    out.close();
                }
            }
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
